from flask import Blueprint, request, jsonify, current_app


from .util.stringToDict import witstringToDict, insolestringToDict
import re


data_bp = Blueprint('data', __name__, url_prefix='/data')

connected_users = {}
sid_to_username = {} # 存储 sid 到 username 的映射，方便在 disconnect 事件中快速查找 username

# 保证bucket存在
def ensure_bucket_exists(inio, bucket_name):
    try:
        buckets = inio.client.buckets_api().find_bucket_by_name(bucket_name)
        if not buckets:
            inio.client.buckets_api().create_bucket(bucket_name=bucket_name, org=inio.org)
    except Exception as e:
        print(f"Error ensuring bucket exists: {e}")
        raise e

@data_bp.route('/witData', methods=['POST'])
def get_witdata():
    try:
        # 获取请求体中的 JSON 数据
        data = request.get_json()

        # 提取 witData 和 username
        wit_data = data.get('witData')
        username = data.get('username')
        mac = data.get('mac')

        #去除冒号导致文件创建失败
        sanitized_mac = re.sub(r'[:]', '_', mac)

        filename = f'{username}_{sanitized_mac}_witData.csv'

        # 将wit_data以csv文件格式保存到本地
        with open(filename, 'a') as file:
            file.write(wit_data + '\n')

        # 将数据保存到influxdb中
        # inio = current_app.influxdb_io
        inio = current_app.config['INFLUXDB_IO']

        # 构造新的 measurement 名称
        measurement_name = f"{sanitized_mac}_witData"

        bucket_name = username
        ensure_bucket_exists(inio, bucket_name)
        witData = witstringToDict(wit_data)

        # inio.write('test_influxdb', measurement_name, witData, {})
        inio.write(bucket_name, measurement_name, witData, {})

        # 打印提取的数据
        # print(f"witData: {wit_data}")
        # print(f"username: {username}")


        # 使用 SocketIO 向 Vue 前端发送数据
        current_app.socketio.emit('response_to_vue', {'username': username, 'data': wit_data}, room='wit_data_room')
        # current_app.socketio.emit('response_to_vue', data, room='wit_data_room')  # 发送到特定房间
        # 返回成功响应
        return jsonify({'message': 'witData received successfully'}), 200

    except Exception as e:
        # 处理异常情况
        error_message = str(e)
        print(error_message)
        return jsonify({'error': error_message}), 400



@data_bp.route('/leftInsoleData', methods=['POST'])
def get_leftInsoledata():
    try:
        # 获取请求体中的 JSON 数据
        data = request.get_json()

        # 提取 witData 和 username
        leftInsole_data = data.get('leftInsoleData')
        username = data.get('username')

        # 以username为文件名，将leftInsoledata以csv文件格式保存到本地
        with open(f'{username}_leftInsole_data.csv', 'a') as file:
            file.write(leftInsole_data + '\n')

        inio = current_app.config['INFLUXDB_IO']
        leftInsoledata = insolestringToDict(leftInsole_data)

        bucket_name = username
        ensure_bucket_exists(inio, bucket_name)
        # 写入influxdb
        inio.write(bucket_name, 'leftInsoleData', leftInsoledata, {})
        # inio.write('test_influxdb', 'leftInsoleData', leftInsoledata, {})

        # 打印提取的数据
        # print(f"leftInsole_data: {leftInsole_data}")
        # print(f"username: {username}")
        current_app.socketio.emit('leftInsole_data_event', {'username': username, 'data': leftInsole_data},
                                  room='wit_data_room')
        # current_app.socketio.emit('leftInsole_data_event', leftInsole_data, room='wit_data_room')
        # 返回成功响应
        return jsonify({'message': 'witData received successfully'}), 200

    except Exception as e:
        # 处理异常情况
        error_message = str(e)
        return jsonify({'error': error_message}), 400

@data_bp.route('/rightInsoleData', methods=['POST'])
def get_rightInsoledata():
    try:
        # 获取请求体中的 JSON 数据
        data = request.get_json()

        # 提取 witData 和 username
        rightInsole_data = data.get('rightInsoleData')
        username = data.get('username')

        # 以username为文件名，将rightInsoledata以csv文件格式保存到本地
        with open(f'{username}_rightInsole_data.csv', 'a') as file:
            file.write(rightInsole_data + '\n')


        inio = current_app.config['INFLUXDB_IO']
        rightInsoledata = insolestringToDict(rightInsole_data)

        bucket_name = username
        ensure_bucket_exists(inio, bucket_name)

        # 写入influxdb
        # inio.write('test_influxdb', 'rightInsoleData', rightInsoledata, {})
        inio.write(bucket_name, 'rightInsoleData', rightInsoledata, {})

        # 打印提取的数据
        # print(f"rightInsole_data: {rightInsole_data}")
        # print(f"username: {username}")
        current_app.socketio.emit('rightInsole_data_event', {'username': username, 'data': rightInsole_data},
                                  room='wit_data_room')
        # current_app.socketio.emit('rightInsole_data_event', rightInsole_data, room='wit_data_room')
        # 返回成功响应
        return jsonify({'message': 'witData received successfully'}), 200

    except Exception as e:
        # 处理异常情况
        error_message = str(e)
        return jsonify({'error': error_message}), 400